/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.anny.evaluate.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.anny.evaluate.entity.AnnyEvaluateConfig;
import com.jeeplus.modules.anny.evaluate.service.AnnyEvaluateConfigService;

/**
 * 积分配置Controller
 * @author yxy
 * @version 2018-10-30
 */
@Controller
@RequestMapping(value = "${adminPath}/anny/evaluate/annyEvaluateConfig")
public class AnnyEvaluateConfigController extends BaseController {

    @Autowired
    private AnnyEvaluateConfigService annyEvaluateConfigService;

    @ModelAttribute
    public AnnyEvaluateConfig get(@RequestParam(required=false) String id) {
        AnnyEvaluateConfig entity = null;
        if (StringUtils.isNotBlank(id)){
            entity = annyEvaluateConfigService.get(id);
        }
        if (entity == null){
            entity = new AnnyEvaluateConfig();
        }
        return entity;
    }

    /**
     * 配置列表页面
     */
    @RequiresPermissions("anny:evaluate:annyEvaluateConfig:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/anny/evaluate/annyEvaluateConfigList";
    }

    /**
     * 配置列表数据
     */
    @ResponseBody
    @RequiresPermissions("anny:evaluate:annyEvaluateConfig:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(AnnyEvaluateConfig annyEvaluateConfig, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<AnnyEvaluateConfig> page = annyEvaluateConfigService.findPage(new Page<AnnyEvaluateConfig>(request, response), annyEvaluateConfig);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑配置表单页面
     */
    @RequiresPermissions(value={"anny:evaluate:annyEvaluateConfig:view","anny:evaluate:annyEvaluateConfig:add","anny:evaluate:annyEvaluateConfig:edit"},logical=Logical.OR)
    @RequestMapping(value = "form")
    public String form(AnnyEvaluateConfig annyEvaluateConfig, Model model) {
        model.addAttribute("annyEvaluateConfig", annyEvaluateConfig);
        if(StringUtils.isBlank(annyEvaluateConfig.getId())){//如果ID是空为添加
            model.addAttribute("isAdd", true);
        }
        return "modules/anny/evaluate/annyEvaluateConfigForm";
    }

    /**
     * 保存配置
     */
    @RequiresPermissions(value={"anny:evaluate:annyEvaluateConfig:add","anny:evaluate:annyEvaluateConfig:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(AnnyEvaluateConfig annyEvaluateConfig, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!validator(annyEvaluateConfig)){
            addMessage(redirectAttributes, "参数不合法");
            return "redirect:"+Global.getAdminPath()+"/anny/evaluate/annyEvaluateConfig/?repage";
        }
        //新增或编辑表单保存
        annyEvaluateConfigService.save(annyEvaluateConfig);//保存
        addMessage(redirectAttributes, "保存配置成功");
        return "redirect:"+Global.getAdminPath()+"/anny/evaluate/annyEvaluateConfig/?repage";
    }

    /**
     * 删除配置
     */
    @ResponseBody
    @RequiresPermissions("anny:evaluate:annyEvaluateConfig:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(AnnyEvaluateConfig annyEvaluateConfig, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        annyEvaluateConfigService.delete(annyEvaluateConfig);
        j.setMsg("删除配置成功");
        return j;
    }

    /**
     * 批量删除配置
     */
    @ResponseBody
    @RequiresPermissions("anny:evaluate:annyEvaluateConfig:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
        for(String id : idArray){
            annyEvaluateConfigService.delete(annyEvaluateConfigService.get(id));
        }
        j.setMsg("删除配置成功");
        return j;
    }

    /**
     * 参数校验 不确定后面会不会加其他类型的配置所以自定义参数校验
     * @param annyEvaluateConfig
     * @return
     */
    private boolean validator(AnnyEvaluateConfig annyEvaluateConfig){
        String configType=annyEvaluateConfig.getConfigType();
        String configValue=annyEvaluateConfig.getConfigValue();
        try {
            switch (configType){
                case "0"://积分比例
                    Double.valueOf(configValue);
                    return true;
                case "1"://激励积分比例
                    Double.valueOf(configValue);
                    return true;
                case "2"://签到积分
                    Integer.valueOf(configValue);
                    return true;
                case "3"://服务费
                    Double.valueOf(configValue);
                    return true;
            }
        }catch (Exception e){
            return false;
        }
        return false;
    }
//
//    /**
//     * 导出excel文件
//     */
//    @ResponseBody
//    @RequiresPermissions("anny:evaluate:annyEvaluateConfig:export")
//    @RequestMapping(value = "export", method=RequestMethod.POST)
//    public AjaxJson exportFile(AnnyEvaluateConfig annyEvaluateConfig, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
//        AjaxJson j = new AjaxJson();
//        try {
//            String fileName = "配置"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
//            Page<AnnyEvaluateConfig> page = annyEvaluateConfigService.findPage(new Page<AnnyEvaluateConfig>(request, response, -1), annyEvaluateConfig);
//            new ExportExcel("配置", AnnyEvaluateConfig.class).setDataList(page.getList()).write(response, fileName).dispose();
//            j.setSuccess(true);
//            j.setMsg("导出成功！");
//            return j;
//        } catch (Exception e) {
//            j.setSuccess(false);
//            j.setMsg("导出配置记录失败！失败信息："+e.getMessage());
//        }
//        return j;
//    }
//
//    /**
//     * 导入Excel数据
//
//     */
//    @RequiresPermissions("anny:evaluate:annyEvaluateConfig:import")
//    @RequestMapping(value = "import", method=RequestMethod.POST)
//    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
//        try {
//            int successNum = 0;
//            int failureNum = 0;
//            StringBuilder failureMsg = new StringBuilder();
//            ImportExcel ei = new ImportExcel(file, 1, 0);
//            List<AnnyEvaluateConfig> list = ei.getDataList(AnnyEvaluateConfig.class);
//            for (AnnyEvaluateConfig annyEvaluateConfig : list){
//                try{
//                    annyEvaluateConfigService.save(annyEvaluateConfig);
//                    successNum++;
//                }catch(ConstraintViolationException ex){
//                    failureNum++;
//                }catch (Exception ex) {
//                    failureNum++;
//                }
//            }
//            if (failureNum>0){
//                failureMsg.insert(0, "，失败 "+failureNum+" 条配置记录。");
//            }
//            addMessage(redirectAttributes, "已成功导入 "+successNum+" 条配置记录"+failureMsg);
//        } catch (Exception e) {
//            addMessage(redirectAttributes, "导入配置失败！失败信息："+e.getMessage());
//        }
//        return "redirect:"+Global.getAdminPath()+"/anny/evaluate/annyEvaluateConfig/?repage";
//    }
//
//    /**
//     * 下载导入配置数据模板
//     */
//    @RequiresPermissions("anny:evaluate:annyEvaluateConfig:import")
//    @RequestMapping(value = "import/template")
//    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
//        try {
//            String fileName = "配置数据导入模板.xlsx";
//            List<AnnyEvaluateConfig> list = Lists.newArrayList();
//            new ExportExcel("配置数据", AnnyEvaluateConfig.class, 1).setDataList(list).write(response, fileName).dispose();
//            return null;
//        } catch (Exception e) {
//            addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
//        }
//        return "redirect:"+Global.getAdminPath()+"/anny/evaluate/annyEvaluateConfig/?repage";
//    }

}